package com.css.chat.netty;

import com.css.chat.logic.chat.message.req.ImgChatToUser;
import com.css.chat.netty.message.AbstractPacket;
import com.css.chat.netty.message.FileUpload;
import io.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class IoSession {

	Logger logger = LoggerFactory.getLogger(this.getClass());

	private volatile int lastLength = 0;
	private int byteRead;

	/** 网络连接channel */
	private Channel channel;

	private String ipAddr;

	private boolean reconnected;

	public IoSession() {

	}

	public IoSession(Channel channel) {
		this.channel = channel;
	}
	
	
	/**
	 * 向客户端发送消息
	 * @param packet
	 */
	public void sendPacket(AbstractPacket packet) {
		if (packet == null) {
			return;
		}
		if (channel != null) {
			channel.writeAndFlush(packet);
		}
	}

	/**
	 * 向客户端发送文件
	 * @param packet
	 */
	public void sendPacketImg(AbstractPacket packet) {
		logger.info("文件执行");
		if (packet == null) {
			return;
		}
		if (channel != null) {
			channel.writeAndFlush(packet);
		}
//		try {
//			if( !(packet instanceof ImgChatToUser)){
//				logger.error("文件类型不正确,应为img");
//			}
//			ImgChatToUser imgChatToUser = (ImgChatToUser) packet;
//			FileUpload fileUpload = imgChatToUser.getFileUpload();
//			RandomAccessFile randomAccessFile = new RandomAccessFile(fileUpload.getFile(), "r");
//			randomAccessFile.seek(fileUpload.getStarPos());
//			// lastLength = (int) randomAccessFile.length() / 10;
//			lastLength = 1024 * 10;
//			byte[] bytes = new byte[lastLength];
//			if ((byteRead = randomAccessFile.read(bytes)) != -1) {
//				fileUpload.setEndPos(byteRead);
//				fileUpload.setBytes(bytes);
//				imgChatToUser.setFileUpload(fileUpload);
//				channel.writeAndFlush(imgChatToUser);//发送消息到服务端
//			} else {
//			}
//			logger.info("channelActive()文件已经读完 {}", byteRead);
//		} catch (FileNotFoundException e) {
//			e.printStackTrace();
//		} catch (IOException i) {
//			i.printStackTrace();
//		}
//		logger.info("channelActive()方法执行结束");
	}

	/**
	 * 向客户端发送文件
	 * @param packet
	 */
	public void sendPacketFile(AbstractPacket packet) {

	}

}
